package com.tuomaxu.factory;

import com.tuomaxu.annotation.Autowired;
import com.tuomaxu.annotation.Component;
import com.tuomaxu.annotation.Transactional;
import com.tuomaxu.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

@Component
public class ProxyFactory {
    @Autowired
    private  TransactionManager transactionManager;

    public Object getCglibProxy(Object obj){
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                //如果method有Transactional注解，就拦截并加入事务
                if(method.isAnnotationPresent(Transactional.class)){
                    Object result = null;
                    try {
                        transactionManager.begin();
                        result =  method.invoke(obj,objects);
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        transactionManager.rollback();
                        throw e;
                    }
                    return result;
                }else {
                    return method.invoke(obj,objects);
                }

            }
        });
    }

}
